package com.itmck.service;

import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.additional.update.impl.LambdaUpdateChainWrapper;
import com.itmck.annotation.Ds;
import com.itmck.dao.StudentMapper;
import com.itmck.dao.UserMapper;
import com.itmck.entity.Student;
import com.itmck.entity.User;
import com.itmck.enums.DataSourceType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 太阳当空照,花儿对我笑
 * <p>
 * Create by M ChangKe 2021/11/17 15:49
 **/
@Service
public class DsChangeImpl implements DsChange {

    @Resource
    private UserMapper userMapper;

    @Resource
    private StudentMapper studentMapper;

    /**
     * 使用默认数据源
     *
     * @return
     */
    @Override
    public List<User> getUserList() {
        return new LambdaQueryChainWrapper<>(userMapper).list();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)//事务
    public int updateUser(User user) {
        boolean update = new LambdaUpdateChainWrapper<>(this.userMapper)
                .eq(User::getName, user.getName())
                .update(user);
//        int i = 1 / 0; //测试事务
        return update ? 1 : 0;
    }

    /**
     * 使用从数据源
     *
     * @return
     */
    @Override
    @Ds(value = DataSourceType.SLAVE)
    public List<Student> getStudentList() {
        return new LambdaQueryChainWrapper<>(studentMapper).list();
    }
}